<template>
  <div class="qq-chat-wrapper">
    <div class="qq-chat-container">
      <div class="qq-chat-header">
        <button type="button" class="back-btn" @click="goBack">返回</button>
        <h2>群聊：{{ groupId }}</h2>
         <!-- ✅ 拉人入群按钮 -->
  <div class="header-btn-group">
    <button class="header-icon-btn" @click="inviteToGroup" title="邀请好友入群">➕</button>
    <button class="header-icon-btn" @click="leaveGroup" title="退出群聊">🚪</button>
  </div>
      </div>

      <div class="qq-chat-area">
        <div class="qq-message-list" ref="messageList">
          <div v-for="(message, index) in messages" :key="index" :class="['qq-message', message.sender === currentUser ? 'self' : 'other']">
            <div class="message-item">
              <div class="qq-message-content">
                <span class="qq-sender">{{ message.sender }}</span>
                <span class="qq-content">{{ message.content }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="qq-input-group">
        <input type="text" v-model="newMessage" @keyup.enter="sendMessage" placeholder="输入群聊消息..." />
         <button @click="toggleEmojiPanel" class="emoji-btn">😀</button>

  <!-- 表情面板 -->
  <div v-if="showEmojiPanel" class="emoji-panel">
    <span v-for="emoji in emojis" :key="emoji" @click="insertEmoji(emoji)" class="emoji-item">
      {{ emoji }}
    </span>
  </div>
        <button class="qq-submit-btn" @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
  <!-- 邀请弹窗 -->
  <!-- 邀请弹窗 -->
 <div v-if="showInviteDialog" class="invite-dialog">
  <div class="invite-dialog-content">
    <h2 class="dialog-title">邀请成员进群</h2>

    <div class="dialog-body">
      <div v-if="inGroupMembers.length" class="user-list">
        <div v-for="user in inGroupMembers" :key="user" class="user-item">
          <label>
            <input
              type="checkbox"
              :value="user"
              v-model="invitedMembers"
              class="user-checkbox"
            />
            {{ user }}
          </label>
        </div>
      </div>
      <div v-else class="no-users">
        当前无可邀请的在线用户
      </div>
    </div>

    <div class="dialog-footer">
      <button class="dialog-btn confirm" @click="sendInvite">确认邀请</button>
      <button class="dialog-btn cancel" @click="cancelInvite">取消</button>
    </div>
  </div>
</div>





</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/stores/userStore';
import websocket from '@/services/websocket.js';
import { ElMessage, ElMessageBox } from 'element-plus';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

const currentUser = userStore.username;
const groupId = route.params.groupId;

const showInviteDialog = ref(false);
const inviteUsername = ref('');

const messages = ref([]);
const newMessage = ref('');

const socket = websocket.initWebSocket();

const onlineUsers = ref([]);        // 所有在线用户
const inGroupMembers = ref([]);     // 当前群内成员
const invitedMembers = ref([]);     // 被选中的邀请用户
const showEmojiPanel = ref(false);

// 常用 emoji 列表
const emojis = [
  '😀', '😂', '😍', '😭', '😡', '👍', '🙏', '🎉', '❤️', '😎',
  '🥰', '😅', '😢', '🤔', '🤯', '👏', '😴', '💯', '🔥', '💡'
];

const toggleEmojiPanel = () => {
  showEmojiPanel.value = !showEmojiPanel.value;
};

const insertEmoji = (emoji) => {
  newMessage.value += emoji;
  showEmojiPanel.value = false;
};


const requestOnlineUsers = () => {
  if (socket && socket.readyState === WebSocket.OPEN) {
    const message = {
      messageType: 8,  // 请求在线用户
      username: currentUser
    };
    socket.send(JSON.stringify(message));
  }
};
const requestGroupMembers = () => {
  const message = {
    messageType: 20, // 请求群内成员
    groupName: groupId,
    onlineUsers: onlineUsers.value // 传递在线用户列表
  };
  socket.send(JSON.stringify(message));
};
const scrollToBottom = () => {
  nextTick(() => {
    const list = document.querySelector('.qq-message-list');
    if (list) list.scrollTop = list.scrollHeight;
  });
};
const cancelInvite = () => {
  showInviteDialog.value = false;
  invitedMembers.value = [];
};

const inviteToGroup = () => {
 showInviteDialog.value = true;
  requestOnlineUsers(); // 获取在线用户
};

const sendMessage = () => {
  if (newMessage.value.trim() && socket.readyState === WebSocket.OPEN) {
    const message = {
      messageType: 5,
      groupId: groupId,
      sender: currentUser,
      content: newMessage.value
    };
    socket.send(JSON.stringify(message));
    messages.value.push({ sender: currentUser, content: newMessage.value });
    newMessage.value = '';
    scrollToBottom();
  }
};

const receiveMessage = (msg) => {
  if (msg.messageType === 5 && msg.groupId === groupId) {
    messages.value.push({ sender: msg.sender, content: msg.content });
    scrollToBottom();
  }

  // 接收在线用户列表
   if (msg.messageType === 9) {
     onlineUsers.value = msg.onlineUsers.filter(user => user !== currentUser); // 过滤掉自己
    requestGroupMembers();
   /*  // 收到在线用户后，立即请求“在线但不在群”的成员
    const checkRequest = {
      messageType: 20, // GroupMemberCheckRequestMessage
      groupName: groupId,
      onlineUsers: msg.onlineUsers.filter(u => u !== currentUser) // 排除自己
    };
    socket.send(JSON.stringify(checkRequest)); */

  } 
  if (msg.messageType === 21) {
    // 后端返回：在线但不在群的成员
    inGroupMembers.value = msg.inGroupMemeber || [];
  }

  // 退出群聊响应
  if (msg.messageType === 17) {
    if (msg.success) {
      ElMessage.success('已退出群聊');
      router.push({ name: 'main' });
    } else {
      ElMessage.error(`退出失败: ${msg.reason}`);
    }
  }
  if(msg.messageType === 15){
     if (msg.success) {
      ElMessage.success('拉入群聊成功');
     
    } else {
      ElMessage.error(`拉入失败失败: ${msg.reason}`);
    }
  }
  
  // 假设 messageType 23 表示历史消息响应
  if (msg.messageType === 23 && Array.isArray(msg.messages)) {
    msg.messages.forEach(item => {
      if (item.groupId === groupId) {
        messages.value.push({
          sender: item.sender,
          content: item.content,
          timestamp: item.timestamp // 如果你想显示时间也可以加进去
        });
      }
    });
    scrollToBottom(); // 滚动到底部
  }


};

onMounted(() => {
  websocket.setGlobalMessageHandler(receiveMessage);
  if (socket && socket.readyState === WebSocket.OPEN) {
    const historyRequest = {
      messageType: 22, // 假设 6 表示请求聊天历史
      groupId: groupId
    };
    socket.send(JSON.stringify(historyRequest));
  }
});

const goBack = () => {
  router.push({ name: 'main' });
};

// 点击“邀请成员”时先请求在线用户


const sendInvite = () => {
  if (!invitedMembers.value.length) {
    ElMessage.warning('请选择要邀请的成员');
    return;
  }

  invitedMembers.value.forEach(invitee => {
    const inviteMessage = {
       messageType: 14, // GROUP_JOIN_REQUEST
    username: invitee,
      groupName: groupId,
    };
    socket.send(JSON.stringify(inviteMessage));
  });

  ElMessage.success(`已邀请 ${invitedMembers.value.join(', ')}`);
  showInviteDialog.value = false;
  invitedMembers.value = [];
};

const leaveGroup = () => {
  ElMessageBox.confirm('确定要退出该群聊吗？', '退出确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      if (socket.readyState === WebSocket.OPEN) {
        const leaveMessage = {
          messageType: 16,
          groupName: groupId,
          username: currentUser
        };
        socket.send(JSON.stringify(leaveMessage));
      }
    })
    .catch(() => {
      ElMessage.info('已取消退出');
    });
};
</script>


<style scoped>
.qq-chat-wrapper {
  min-height: 100vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: url("@/assets/re_bg.png");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: absolute;
  top: 0;
  left: 0;
}

.qq-chat-container {
  width: 100%;
  max-width: 800px;
  height: 600px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}



.back-btn:hover {
  background-color: #16a085;
  transform: translateY(-5px);
}

.back-btn:active {
  background-color: #1abc9c;
  transform: translateY(2px);
}

.qq-submit-btn {
  padding: 12px 20px;
  background-color: #1abc9c;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  font-weight: bold;
  transition: background-color 0.3s, transform 0.2s;
  white-space: nowrap;
}

.qq-submit-btn:hover {
  background-color: #16a085;
  transform: translateY(-5px);
}

.qq-submit-btn:active {
  background-color: #1abc9c;
  transform: translateY(2px);
}

.qq-chat-area {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f5f6f7;
}

.qq-message-list {
  display: flex;
  flex-direction: column;
}

.qq-message {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.qq-message.self {
  flex-direction: row-reverse;
}

.message-item {
  display: flex;
  align-items: flex-start;
}

.qq-message-content {
  width: 300px;
  min-height: 40px;
  max-height: 300px;
  padding: 10px 15px;
  border-radius: 6px;
  background-color: white;
  overflow-y: auto;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.qq-message.other .qq-message-content {
  background-color: white;
}

.qq-sender {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
  display: block;
  font-weight: bold;
}

.qq-content {
  display: block;
  margin-top: 5px;
}

.qq-input-group {
  display: flex;
  width: 100%;
  padding: 10px;
  background-color: white;
  border-top: 1px solid #e8e8e8;
}

.qq-input-group input {
  flex: 1;
  padding: 10px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  margin-right: 10px;
}

.qq-chat-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.back-btn {
  padding: 10px 20px;
  background-color: #1abc9c;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  font-weight: bold;
  transition: background-color 0.3s, transform 0.2s;
}



/* 新增：右侧按钮容器 */
.header-btn-group {
  display: flex;
  gap: 10px;
}

.header-icon-btn {
  background: transparent;
  border: none;
  font-size: 22px;
  cursor: pointer;
  transition: transform 0.2s;
}

.header-icon-btn:hover {
  transform: scale(1.2);
}
.invite-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.invite-dialog-content {
  background: #fff;
  border-radius: 10px;
  padding: 20px 30px;
  width: 400px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.dialog-title {
  margin-bottom: 15px;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
}

.dialog-body {
  margin-bottom: 20px;
}

.user-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.user-item {
  display: flex;
  align-items: center;
}

.user-checkbox {
  margin-right: 8px;
}

.no-users {
  text-align: center;
  color: #999;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.dialog-btn {
  flex: 1;
  padding: 10px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
}

.dialog-btn.confirm {
  background-color: #409eff;
  color: #fff;
}

.dialog-btn.cancel {
  background-color: #f5f5f5;
  color: #333;
}
.emoji-btn {
  background: none;
  border: none;
  font-size: 22px;
  cursor: pointer;
  margin-right: 10px;
}

.emoji-panel {
  position: absolute;
  bottom: 60px;
  left: 20px;
  background: white;
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
  z-index: 10;
}

.emoji-item {
  cursor: pointer;
  font-size: 20px;
}

</style>
